<template>
  <div class="table-box">
    <ProTable ref="proTable" :columns="columns" :request-api="queryCommodityPageList">
      <!-- 表格 header 按钮 -->
      <template #tableHeader>
        <el-button type="primary" :icon="CirclePlus" @click="insertDialogVisible = true">新增商品</el-button>
      </template>
      <template #createDate="scope">
        {{ scope.row.createDate.replace("T", " ").split(".")[0] }}
      </template>
      <template #updateDate="scope">
        {{ scope.row.updateDate.replace("T", " ").split(".")[0] }}
      </template>
      <!-- 表格操作 -->
      <template #operation="scope">
        <el-button type="primary" link :icon="EditPen" @click="openUpdateDialog(scope.row)">编辑</el-button>
        <el-button type="primary" link :icon="Delete" @click="removeCommodity(scope.row)">删除</el-button>
      </template>
    </ProTable>
    <!-- 新增对话框 -->
    <el-dialog width="50%" title="新增商品分类" v-model="insertDialogVisible">
      <el-form ref="insertFormRef" :model="insertParam" :rules="ruleForm" label-width="150px" class="demo-ruleForm">
        <el-row :gutter="15">
          <el-col :span="12">
            <el-form-item label="商品名称" prop="commodityName">
              <el-input v-model="insertParam.commodityName" placeholder="请输入商品名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="商品编码">
              <el-input v-model="insertParam.commodityCode" placeholder="请输入商品编码" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="15">
          <el-col :span="12">
            <el-form-item label="商品类别">
              <el-select v-model="insertParam.categoryId" @change="insertCommodityCategoryFilter">
                <el-option
                  v-for="item in commodityCategory"
                  :key="item.commodityCategoryId"
                  :label="item.commodityCategoryName"
                  :value="item.commodityCategoryId"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="价格">
              <el-input-number v-model="insertParam.price"></el-input-number>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="15">
          <el-col :span="12">
            <el-form-item label="单位">
              <el-input v-model="insertParam.unit"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态">
              <el-radio-group v-model="insertParam.status">
                <el-radio :label="0" :value="0">禁用</el-radio>
                <el-radio :label="1" :value="1">正常</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="15">
          <el-col :span="12">
            <el-form-item label="厂家">
              <el-input v-model="insertParam.manufacturer"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="库存">
              <el-input-number v-model="insertParam.commodityStock"></el-input-number>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="商品图片">
          <UploadImg v-model:image-url="insertParam.imageUrl">
            <template #empty>
              <el-icon><Picture /></el-icon>
              <span>请上传图片</span>
            </template>
          </UploadImg>
        </el-form-item>
        <el-form-item label="商品描述">
          <el-input v-model="insertParam.description" type="textarea"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="insertDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="addCOmmodity(insertFormRef)">新增</el-button>
        </span>
      </template>
    </el-dialog>

    <el-dialog width="50%" title="修改商品分类" v-model="updateDialogVisible">
      <el-form ref="updateFormRef" :model="updateParam" :rules="ruleForm" label-width="150px" class="demo-ruleForm">
        <el-row :gutter="15">
          <el-col :span="12">
            <el-form-item label="商品名称" prop="commodityName">
              <el-input v-model="updateParam.commodityName" placeholder="请输入商品名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="商品编码">
              <el-input v-model="updateParam.commodityCode" placeholder="请输入商品编码" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="15">
          <el-col :span="12">
            <el-form-item label="商品类别">
              <el-select v-model="updateParam.categoryId" @change="updateCommodityCategoryFilter">
                <el-option
                  v-for="item in commodityCategory"
                  :key="item.commodityCategoryId"
                  :label="item.commodityCategoryName"
                  :value="item.commodityCategoryId"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="价格">
              <el-input-number v-model="updateParam.price"></el-input-number>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="15">
          <el-col :span="12">
            <el-form-item label="单位">
              <el-input v-model="updateParam.unit"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态">
              <el-radio-group v-model="updateParam.status">
                <el-radio :label="0" :value="0">禁用</el-radio>
                <el-radio :label="1" :value="1">正常</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="15">
          <el-col :span="12">
            <el-form-item label="厂家">
              <el-input v-model="updateParam.manufacturer"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="库存">
              <el-input-number v-model="updateParam.commodityStock"></el-input-number>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="商品图片">
          <UploadImg v-model:image-url="updateParam.imageUrl">
            <template #empty>
              <el-icon><Picture /></el-icon>
              <span>请上传图片</span>
            </template>
          </UploadImg>
        </el-form-item>
        <el-form-item label="商品描述">
          <el-input v-model="insertParam.description" type="textarea"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="updateDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="updateCommodity(updateFormRef)">修改</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>
<script setup lang="ts" name="commodityCategory">
import { ref, reactive, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import type { ColProps, FormInstance, FormRules } from "element-plus";
import { CirclePlus, Delete, EditPen, Download, Upload, View, Refresh, ElementPlus, Picture } from "@element-plus/icons-vue";
import ProTable from "@/components/ProTable/index.vue";
import UploadImg from "@/components/Upload/Img.vue";
import { ProTableInstance, ColumnProps } from "@/components/ProTable/interface";
import { statusEnum, statusFieldNames } from "@/enums/httpEnum";
import { CreateCommodityParam, EditCommodityParam, HxCommodity, HxCommodityCategory } from "@/api/interface/commodity";
import {
  createCommodity,
  deleteCommodity,
  editCommodity,
  queryCommodityCategoryList,
  queryCommodityPageList
} from "@/api/modules/commodity";

const proTable = ref<ProTableInstance>();

const insertDialogVisible = ref(false);

const updateDialogVisible = ref(false);

const insertFormRef = ref<FormInstance>();

const updateFormRef = ref<FormInstance>();

/** 新增初始化参数 */
const initInsertParam: CreateCommodityParam = {
  commodityName: "",
  commodityCode: "",
  commodityStock: 0,
  price: 0,
  categoryId: "",
  categoryName: "",
  status: 1,
  imageUrl: ""
};

/** 新增参数 */
const insertParam = reactive<CreateCommodityParam>({
  commodityName: "",
  commodityCode: "",
  commodityStock: 0,
  price: 0,
  categoryId: "",
  categoryName: "",
  status: 1,
  imageUrl: ""
});

/** 修改参数 */
const updateParam = reactive<EditCommodityParam>({
  commodityId: "",
  commodityName: "",
  commodityCode: "",
  commodityStock: 0,
  price: 0,
  categoryId: "",
  categoryName: "",
  imageUrl: "",
  status: 1
});

/** form表单验证规则 */
const ruleForm = reactive<FormRules>({
  commodityCategoryName: [{ required: true, message: "请输入商品名称", trigger: "change" }]
});

const commodityCategory = ref<HxCommodityCategory[]>([]);

onMounted(async () => {
  await refreshCommodityCategory();
});

const refreshCommodityCategory = async () => {
  const { data } = await queryCommodityCategoryList({});
  commodityCategory.value = [...data];
};

const insertCommodityCategoryFilter = (val: string) => {
  if (val) {
    insertParam.categoryName = commodityCategory.value.find(p => p.commodityCategoryId === val)?.commodityCategoryName;
  }
};

const updateCommodityCategoryFilter = (val: string) => {
  if (val) {
    updateParam.categoryName = commodityCategory.value.find(p => p.commodityCategoryId === val)?.commodityCategoryName;
  }
};

/** 🧍表格配置项 */
const columns = reactive<ColumnProps<HxCommodity>[]>([
  { type: "selection", fixed: "left", width: 70 },
  { type: "index", label: "", width: 80 },
  {
    prop: "commodityName",
    label: "商品名称",
    width: 150,
    search: { el: "input", tooltip: "请输入商品名称" }
  },
  {
    prop: "commodityCode",
    label: "商品编码",
    width: 120
  },

  {
    prop: "status",
    label: "状态",
    tag: true,
    enum: statusEnum,
    search: { el: "select", props: { filterable: true } },
    fieldNames: statusFieldNames
  },
  {
    prop: "unit",
    label: "单位"
  },
  {
    prop: "price",
    label: "价格"
  },
  {
    prop: "categoryName",
    label: "商品类别",
    width: 130
  },
  {
    prop: "manufacturer",
    label: "厂家"
  },
  {
    prop: "createDate",
    label: "创建时间",
    width: 200
  },
  {
    prop: "updateDate",
    label: "修改时间",
    width: 200
  },
  { prop: "operation", label: "操作", fixed: "right", width: 330 }
]);

/** 新增商品分类 */
const addCOmmodity = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      await createCommodity(insertParam);
      ElMessage.success("新增商品成功");
      insertDialogVisible.value = false;
      Object.assign(insertParam, initInsertParam);
      proTable.value?.getTableList();
    } else {
      ElMessage.error("请填入必填数据");
    }
  });
};

/** 打开修改对话框 */
const openUpdateDialog = (param: HxCommodity) => {
  updateDialogVisible.value = true;
  Object.assign(updateParam, param);
};

/** 修改商品信息 */
const updateCommodity = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      await editCommodity(updateParam);

      ElMessage.success("修改商品信息成功");
      updateDialogVisible.value = false;
      Object.assign(insertParam, initInsertParam);
      proTable.value?.getTableList();
    } else {
      ElMessage.error("请填入必填数据");
    }
  });
};

/** 删除商品 */
const removeCommodity = async (param: HxCommodity) => {
  await deleteCommodity({ commodityId: param.commodityId });
  ElMessage.success("删除成功");
  proTable.value?.getTableList();
};
</script>
